import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { apiV1AdminAuthLogin, adminAuthLogout, adminAuthProfile } from '@/api/admin-api/auth';

interface User {
  id: number;
  account: string;
  name: string;
  email?: string;
  role: string;
  status: number;
  created_at: string;
  updated_at: string;
}

interface AuthState {
  token: string | null;
  user: User | null;
  isAuthenticated: boolean;
  permissions: string[];
  
  // Actions
  login: (account: string, password: string) => Promise<void>;
  logout: () => void;
  refreshUserInfo: () => Promise<void>;
  updateUser: (user: Partial<User>) => void;
  setToken: (token: string) => void;
  clearAuth: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      token: null,
      user: null,
      isAuthenticated: false,
      permissions: [],
      
      login: async (account: string, password: string) => {
        try {
          const response = await apiV1AdminAuthLogin({
            username: account,
            password,
          });

          const { token, user, permissions } = response;

          set({
            token,
            user,
            isAuthenticated: true,
            permissions: permissions || [],
          });

          localStorage.setItem('token', token);
        } catch (error) {
          // 登录失败时清理状态
          get().clearAuth();
          throw error;
        }
      },
      
      logout: () => {
        try {
          // 尝试调用后端登出接口，但不等待结果
          adminAuthLogout().catch(() => {
            // 忽略登出接口错误，因为可能 token 已失效
          });
        } catch (error) {
          // 忽略错误
        }

        get().clearAuth();
      },
      
      refreshUserInfo: async () => {
        try {
          const response = await adminAuthProfile();
          set({ user: response });
        } catch (error) {
          console.error('刷新用户信息失败:', error);
          // 如果是认证错误，清理状态
          if (error?.response?.status === 401) {
            get().clearAuth();
          }
        }
      },
      
      updateUser: (userData: Partial<User>) => {
        set(state => ({
          user: state.user ? { ...state.user, ...userData } : null,
        }));
      },
      
      setToken: (token: string) => {
        set({ token, isAuthenticated: true });
        localStorage.setItem('token', token);
      },
      
      clearAuth: () => {
        set({
          token: null,
          user: null,
          isAuthenticated: false,
          permissions: [],
        });
        localStorage.removeItem('token');
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        token: state.token,
        user: state.user,
        isAuthenticated: state.isAuthenticated,
        permissions: state.permissions,
      }),
      // 在 hydrate 时验证 token 有效性
      onRehydrateStorage: () => (state) => {
        if (state?.token && state?.isAuthenticated) {
          // 验证存储的 token 是否与 localStorage 一致
          const storedToken = localStorage.getItem('token');
          if (storedToken !== state.token) {
            state.clearAuth();
          }
        }
      },
    }
  )
);